<template>
  <div class="jobs-management">
    <el-card>
      <template #header>作业历史</template>
      <div class="jobs-content">
        <KyTable
          ref="tableRef"
          :getData="getJobsList"
          :show-select="true"
          :showAdvancedSearch="true"
        >
          <template #table-action>
            <div class="os-upgrade-table-action">
              <el-button type="primary" @click="handleRefresh">刷新</el-button>
              <el-button
                type="danger"
                :disabled="tableRef?.select_number === 0"
                @click="handleDelete"
                >删除</el-button
              >
              <!-- 设置 -->
              <el-button
                class="ky-item-button"
                @click.stop="handleCustomColumn"
                name="plugin-os-upgrade:operation"
                type="default"
              >
                <el-icon><Setting /></el-icon>
              </el-button>
            </div>
          </template>
          <!-- table表格 -->
          <template #table>
            <el-table-column prop="job_name" :label="'作业名称'" />
            <el-table-column prop="modify_user" :label="'执行人'" />
            <el-table-column prop="job_type" :label="'执行方式'" />
            <el-table-column prop="start_time" :label="'开始时间'" />
            <el-table-column prop="end_time" :label="'结束时间'" />
            <el-table-column prop="total_time" :label="'总耗时'" />
            <el-table-column prop="job_status" :label="'作业状态'" />
            <el-table-column prop="targetSystem" :label="'操作'">
              <template #default="{ row }">
                <el-button size="small" @click="reRun(row)">重新执行</el-button>
                <el-button size="small" @click="handleDetail(row)">查看详情</el-button>
              </template></el-table-column
            >
          </template>

          <template #empty>
            <div>
              <router-link to="/workflow/addWorkflow">
                <span role="button" class="link-btn"> 创建一个作业吧! </span>
              </router-link>
            </div>
          </template>
        </KyTable>
      </div>
    </el-card>
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      :before-close="handleCloseDialog"
      :width="dialogWidth"
    >
      <CustomColumn
        v-if="rwType === 'custom_list'"
        @click="handleCloseDialog"
        :customData="colData"
        :rawData="rawData"
        @handleOk="handleCustomColumnOk"
      ></CustomColumn>
    </el-dialog>
    <!-- 抽屉组件 -->
    <el-drawer v-model="drawerVisible" title="任务执行详情" :size="600" direction="rtl">
      <JobDetail :job_id />
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, defineAsyncComponent } from 'vue';
import { getJobsList, deleteJobs, reRunJob, getJobDetail } from '@/api/jobs';
import { ElMessage, ElMessageBox } from 'element-plus';
import { RespCodeOk, Result } from '@/utils/request';
import { JobItem } from '@/types/jobs';
const KyTable = defineAsyncComponent(() => import('@/components/KyTable/index.vue'));
const tableRef = ref<InstanceType<typeof KyTable> | null>(null);
const CustomColumn = defineAsyncComponent(() => import('@/components/customColumn/index.vue'));
const JobDetail = defineAsyncComponent(() => import('./components/detail.vue'));

const dialogVisible = ref<boolean>(false);
const dialogTitle = ref<string>('自定义列');
const dialogWidth = ref<string>('50%');
const rwType = ref<string>('custom_list');
const colData = ref<any>([]);
const rawData = ref<any>([]);
// 抽屉显示状态
const drawerVisible = ref(false);

const handleCustomColumnOk = (val: any) => {
  handleCloseDialog();
};
const handleCloseDialog = () => {
  dialogVisible.value = false;
  rwType.value = '';
};
// 编排管理组件逻辑
const handleCustomColumn = () => {
  getCustomColumnFun();
  rwType.value = 'custom_list';
  dialogVisible.value = true;
  dialogTitle.value = '自定义列';
};
const getCustomColumnFun = async () => {
  colData.value = [
    { name: 'name', label: '编排名称', visible: true },
    { name: 'last_step_num', label: '任务数', visible: true },
    { name: 'publish_status', label: '发布状态', visible: true },
    { name: 'modify_user', label: '修改人', visible: true },
    { name: 'modify_time', label: '修改时间', visible: true },
  ];

  // 为rawData设置初始值，确保与colData结构一致
  rawData.value = JSON.parse(JSON.stringify(colData.value));
};
// 刷新
const handleRefresh = () => {
  tableRef.value?.refresh();
};

// 删除
const handleDelete = () => {
  const rows = tableRef.value?.selectRow;
  ElMessageBox.confirm('确定删除选中的作业吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      // 确认删除
      let res: Result = await deleteJobs(rows);
      if (res.code === RespCodeOk) {
        ElMessage.success('删除成功');
      } else {
        ElMessage.error('删除失败');
      }
    })
    .catch((error) => {
      // 取消删除
      ElMessage.error('删除失败');
      console.log(error);
    });
};

// 重新执行
const reRun = async (row: JobItem) => {
  if (!row) return;
  let { job_id, retry_step, retry_hosts } = row;
  let params = {
    job_id,
    step_num: retry_step,
    reuse_env: false,
    retry_hosts,
  };
  let res: Result = await reRunJob(params);
  if (res.code === RespCodeOk) {
    handleRefresh();
    ElMessage.success('成功');
  } else {
    ElMessage.error('执行失败');
  }
};

// 查看详情
const job_id = ref('');
const handleDetail = async (row: JobItem) => {
  if (!row) return;
  job_id.value = row.job_id;
  drawerVisible.value = true;
};
</script>

<style scoped lang="scss"></style>
